/*
  学习目标：使用subscribe监听sore数据的变化
  语法: const 解除监听的函数 = store.subscribe(() => {  可以获取到更新后的值}) 
*/

import { legacy_createStore as createStore } from 'redux';

const store = createStore(function (state = { count: 0 }, action) {
  if (action.type === 'add') {
    return { ...state, count: state.count + 1 };
  }

  if (action.type === 'des') {
    return { ...state, count: state.count - 1 };
  }
  return state;
});

store.dispatch({ type: 'add' });
store.dispatch({ type: 'add' });

// 💥 subscribe需要再dispatch触发前, 开启监听
const unFn = store.subscribe(() => {
  console.log(store.getState(), 'getState');
});

store.dispatch({ type: 'add' });
store.dispatch({ type: 'add' });
store.dispatch({ type: 'des' });
// unFn是取消监听的函数
unFn();
store.dispatch({ type: 'des' });
